<?php

class ReceivingAssigningController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(

			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','view','admin','delete' , 'report' , 'reportSubmit' , 'reportExcel'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$model = $this->loadModel($id);
		$params = array('user_id'=>$model->user_id);
		if(!Yii::app()->user->checkAccess('readReceivingAssigning', $params))
		{
			throw new CHttpException(403,'Bạn không có quyền hạn truy cập trang này.');
		}
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new ReceivingAssigning;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['ReceivingAssigning']))
		{
			if(!Yii::app()->user->checkAccess('createReceivingAssigning'))
			{
				throw new CHttpException(403,'Bạn không có quyền hạn truy cập trang này.');
			}
			$model->attributes=$_POST['ReceivingAssigning'];
			$model->user_id = Yii::app()->user->id;
			if ($model->validate()){
				$model->received_date = Common::stringToMySQLDate($model->received_date);
				if($model->save(false))
					$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model = $this->loadModel($id);
		$params = array('user_id'=>$model->user_id);
		if(!Yii::app()->user->checkAccess('readReceivingAssigning', $params))
		{
			throw new CHttpException(403,'Bạn không có quyền hạn truy cập trang này.');
		}
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['ReceivingAssigning']))
		{
			$model->attributes=$_POST['ReceivingAssigning'];
			if ($model->validate()){
				$model->received_date = Common::stringToMySQLDate($model->received_date);
				if($model->save(false))
					$this->redirect(array('view','id'=>$model->id));
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model = $this->loadModel($id);
		$params = array('user_id'=>$model->user_id);
		if(!Yii::app()->user->checkAccess('readReceivingAssigning', $params))
		{
			throw new CHttpException(403,'Bạn không có quyền hạn truy cập trang này.');
		}
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->deleteEx();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}


	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		if(!Yii::app()->user->checkAccess('manager'))
		{
			throw new CHttpException(403,'Bạn không có quyền hạn truy cập trang này.');
		}
		$model=new ReceivingAssigning('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['ReceivingAssigning']))
			$model->attributes=$_GET['ReceivingAssigning'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
        
        /**
         * statistic report receivingAssigning
         */
        
        public function actionReport()
        {
            if(!Yii::app()->user->checkAccess('manager'))
            {
		throw new CHttpException(403,'Bạn không có quyền hạn truy cập trang này.');
            }
            $model=new ReceivingAssigning;//('searchByTime');
            $model->unsetAttributes();  // clear any default values
             $submit = false;
            if(!isset($_GET['ReceivingAssigning']))
            {
               $submit = false;
            }
            $time = array();
            if(isset($_GET['ReceivingAssigning']))
            {				
		//$model->attributes=$_POST['Job'];
		$time = $_GET['ReceivingAssigning'];
		$date1 = $time['date1'];
		$date2 = $time['date2'];
		$model->date1 = $date1;
		$model->date2 = $date2;	
		$submit = true;
            }
		
            $this->render('report',array(
		'model'=>$model,
		'time' => $time ,
		'submit'=>$submit 
            ));
        }
        
        public function actionReportSubmit()
        {
            if(!Yii::app()->user->checkAccess('manager'))
            {
		throw new CHttpException(403,'Bạn không có quyền hạn truy cập trang này.');
            }
            $model=new ReceivingAssigning;//('searchByTime');
            $model->unsetAttributes();  // clear any default values
            $submit = false;
            $time = array();
            if(isset($_GET['ReceivingAssigning']))
            {		                
		//$model->attributes=$_POST['Job'];
		$time = $_GET['ReceivingAssigning'];
               // die(print_r($time));
		$date1 = $time['date1'];
		$date2 = $time['date2'];
		$model->date1 = $date1;
		$model->date2 = $date2;	
		$submit = true;
            }
		
            $this->render('report',array(
		'model'=>$model,
		'time' => $time ,
		'submit'=>$submit 
            ));
        }
        
        /**
	 * Export statistics by time
	 */
	
	public function actionReportExcel()
	{
		if(!Yii::app()->user->checkAccess('manager'))
		{
			throw new CHttpException(403,'Bạn không có quyền hạn truy cập trang này.');
		}
		$model=new ReceivingAssigning;//('searchByTime');
		$model->unsetAttributes();  // clear any default values
		$time = array();
		if(isset($_GET['ReceivingAssigning']))
		{			
			$time = $_GET['ReceivingAssigning'];
			$date1 = $time['date1'];
			$date2 = $time['date2'];
			$model->date1 = $date1;
			$model->date2 = $date2;		
			$listReceivingAssigning = $model->getListReceivingAssigningByTime($date1 , $date2);	  
                       // die(print_r($listReceivingAssigning));
		}
		$this->exportReceivingAssigningExcel($listReceivingAssigning , $date1 , $date2 , Yii::app()->user->id);
		//$error = 'Dữ liệu trống';
		$submit = true;
		$this->render('statisticsTime',array(
			'model'=>$model,
			'time' => $time ,
			//'error' => $error ,
			'submit' => $submit
		));
	}
        
        /*
         * Export to excel
         */
        function exportReceivingAssigningExcel($data , $date1 , $date2 , $user_id)
        {
                $objPHPExcel = Yii::app()->excel;
		$objPHPExcel->setActiveSheetIndex(0);
		
		$sharedStyle1 = new PHPExcel_Style();
		$sharedStyle2 = new PHPExcel_Style();
		$sharedStyle3 = new PHPExcel_Style();
		$sharedStyle4 = new PHPExcel_Style();
		$head = new PHPExcel_Style();
                $head1 = new PHPExcel_Style();
                $end = new PHPExcel_Style();
		$sharedStyle1->applyFromArray(
			array('fill' 	=> array(
										'type'		=> PHPExcel_Style_Fill::FILL_SOLID,
										'color'		=> array('argb' => 'FFCCFFCC')
									),
				  'borders' => array(
										'bottom'	=> array('style' => PHPExcel_Style_Border::BORDER_THIN),
										'right'		=> array('style' => PHPExcel_Style_Border::BORDER_MEDIUM)
									)
				 ));

		$sharedStyle2->applyFromArray(
			array('fill' 	=> array(
										'type'		=> PHPExcel_Style_Fill::FILL_SOLID,
										'color'		=> array('argb' => 'FFFFFF00')
									),
					'borders' => array(
						'bottom'     => array(
							'style' => PHPExcel_Style_Border::BORDER_DASHDOT
						) ,
						'top'     => array(
							'style' => PHPExcel_Style_Border::BORDER_DOTTED
						) ,
						'right'		=> array('style' => PHPExcel_Style_Border::BORDER_THIN)
					),
					'alignment' => array(
						'wrap' => true
						)		  
				 ));
				 
		$sharedStyle3->applyFromArray(
			array(
                                'fill' 	=> array(
										'type'		=> PHPExcel_Style_Fill::FILL_SOLID,
										'color'		=> array('argb' => 'D3D3D3D3')
									),
                                         'borders' => array(
						'bottom'     => array(
							'style' => PHPExcel_Style_Border::BORDER_THIN ,
                                                        'color' => array('argb' => '00000000'),
						) ,
                                             'right'     => array(
							'style' => PHPExcel_Style_Border::BORDER_THIN ,
                                                        'color' => array('argb' => '00000000'),
						) ,
					),                               
					
					'alignment' => array(
						'wrap' => true
						)		  
				 ));		 
		$sharedStyle4->applyFromArray(
			array('fill' 	=> array(
										'type'		=> PHPExcel_Style_Fill::FILL_SOLID,										
									),
					'borders' => array(
						'bottom'     => array(
							'style' => PHPExcel_Style_Border::BORDER_DOTTED
						) ,
						'top'     => array(
							'style' => PHPExcel_Style_Border::BORDER_DOTTED
						) ,
						'right'		=> array('style' => PHPExcel_Style_Border::BORDER_THIN)
					),
					'alignment' => array(
						'wrap' => true
						)		  
				 ));
		$styleThickBrownBorderOutline = array(
			'borders' => array(
				'outline' => array(
					'style' => PHPExcel_Style_Border::BORDER_THICK,
					'color' => array('argb' => 'FF993300'),
				),
			),
		);

		$styleThinBlackBorderOutline = array(
			'borders' => array(
				'top' => array(
					'style' => PHPExcel_Style_Border::BORDER_THIN,
					'color' => array('argb' => 'FF000000'),
				),
				'right' => array(
					'style' => PHPExcel_Style_Border::BORDER_THIN,
					'color' => array('argb' => 'FF000000'),
				),
				'bottom' => array(
					'style' => PHPExcel_Style_Border::BORDER_DOTTED,
					'color' => array('argb' => 'FF000000'),
				),
			),
		);
                
                $head->applyFromArray(
			array('fill' 	=> array(
										'type'		=> PHPExcel_Style_Fill::FILL_SOLID,
										'color'		=> array('argb' => 'D3D3D3D3')
									),
                                         'borders' => array(
						'bottom'     => array(
							'style' => PHPExcel_Style_Border::BORDER_THIN ,
                                                        'color' => array('argb' => 'FFFFFFFF'),
						) ,	
                                             'right'     => array(
							'style' => PHPExcel_Style_Border::BORDER_THIN ,
                                                        'color' => array('argb' => '00000000'),
						) ,
					),                               
					
					'alignment' => array(
						'wrap' => true
						)		  
				 ));
                 $head1->applyFromArray(
			array('fill' 	=> array(
										'type'		=> PHPExcel_Style_Fill::FILL_SOLID,
										'color'		=> array('argb' => 'D3D3D3D3')
									),
                                        'borders' => array(
                                               
                                                'right' => array(
                                                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                                                        'color' => array('argb' => 'FF000000'),
                                                ),
                                                
                                        ),                                    
                                        
					'alignment' => array(
						'wrap' => true
						)		  
				 ));
                 
               $end->applyFromArray(
			array(
                                        'borders' => array(
                                               
                                                'bottom' => array(
                                                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                                                        'color' => array('argb' => 'FF000000'),
                                                ),
                                            'right' => array(
                                                        'style' => PHPExcel_Style_Border::BORDER_THIN,
                                                        'color' => array('argb' => 'FF000000'),
                                                ),
                                                
                                        ),                                    
                                        
					'alignment' => array(
						'wrap' => true
						)		  
				 ));
                
                 
                $user = new User();
		$arrayUser = $user->getUser($user_id);	
		$fullName = $arrayUser[0]->attributes['full_name'];
                
		$objPHPExcel->getActiveSheet()->setCellValue('A1', 'BÁO CÁO CÔNG VIỆC THỰC HIỆN NHÓM  HỖ TRỢ USER');	
                $objPHPExcel->getActiveSheet()->setCellValue('A2', 'Từ ngày ' . $date1 . ' - ' . $date2 );	
		 $objPHPExcel->getActiveSheet()->setCellValue('A3', 'Nhân viên thực hiện: ' . $fullName );
		$objPHPExcel->getActiveSheet()->setCellValue('A4', "Ngày");
		$objPHPExcel->getActiveSheet()->setCellValue('B4', "Tiếp nhận + Phân công");
		$objPHPExcel->getActiveSheet()->setCellValue('B5', "Phòng ban");
		$objPHPExcel->getActiveSheet()->setCellValue('C5', "Nội dung");
		$objPHPExcel->getActiveSheet()->setCellValue('D5', "Nhân sự");
			
			
		//
		$i = 6;
		foreach($data as $values)
		{	                   
                   //die(print_r($values->attributes['received_date']));
                   $received_date = Common::mySQLDatetimeToString($values['received_date']);                
			$objPHPExcel->getActiveSheet()->setCellValue("A$i",$received_date);
			$objPHPExcel->getActiveSheet()->setCellValue("B$i", $values['department']);
			$objPHPExcel->getActiveSheet()->setCellValue("C$i", $values['detail']);
			$objPHPExcel->getActiveSheet()->setCellValue("D$i", $values['operator']);					
			$i++;
		}
                  
                
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
		$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(40);
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
		
		
		//$objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight();
		
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(12);
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('Arial');
		$objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setName('Arial');		
		$objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->setName('Arial');		
		$objPHPExcel->getActiveSheet()->getStyle('C2')->getFont()->setName('Arial');		
		$objPHPExcel->getActiveSheet()->getStyle('D2')->getFont()->setName('Arial');
                
		$objPHPExcel->getActiveSheet()->setSharedStyle($head1 , "A4:A5");
                 $objPHPExcel->getActiveSheet()->setSharedStyle($head1 , "D4:D5");
		$objPHPExcel->getActiveSheet()->setSharedStyle($head , "B4:D4");
                $objPHPExcel->getActiveSheet()->setSharedStyle($head , "B5:D5");   
               
                $i--;               
                $objPHPExcel->getActiveSheet()->setSharedStyle($end , "A$i:D$i");
                $i--;
               
		$objPHPExcel->getActiveSheet()->setSharedStyle($sharedStyle4, "A6:A$i");
		$objPHPExcel->getActiveSheet()->setSharedStyle($sharedStyle4, "B6:B$i");
		$objPHPExcel->getActiveSheet()->setSharedStyle($sharedStyle4, "C6:C$i");
		$objPHPExcel->getActiveSheet()->setSharedStyle($sharedStyle4, "D6:D$i");
                
                $objPHPExcel->getActiveSheet()->setSharedStyle($sharedStyle3, "A5:D5");
                // $objPHPExcel->getActiveSheet()->setSharedStyle($end , "A$i:D$i");
                    //die(print $i
                
		
		$objPHPExcel->getActiveSheet()->mergeCells('A1:D1');
		$objPHPExcel->getActiveSheet()->mergeCells('A2:D2');
                $objPHPExcel->getActiveSheet()->mergeCells('A3:D3');
                $objPHPExcel->getActiveSheet()->mergeCells('B4:D4');
                //$objPHPExcel->getActiveSheet()->mergeRows('A4:D5');
                
		$objPHPExcel->getActiveSheet()->getStyle('A2')->getFont()->setBold(true);
                $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setBold(true);
                 $objPHPExcel->getActiveSheet()->getStyle('A4')->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->getStyle('B4')->getFont()->setBold(true);
                $objPHPExcel->getActiveSheet()->getStyle('B5')->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->getStyle('C5')->getFont()->setBold(true);
		$objPHPExcel->getActiveSheet()->getStyle('D5')->getFont()->setBold(true);
		
		$objPHPExcel->getActiveSheet()->getStyle("A6:A$i")->getAlignment()->applyFromArray(
                             array(
                                 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
                                 'vertical'   => PHPExcel_Style_Alignment::VERTICAL_TOP,
                                 'rotation'   => 0,
                                 'wrap'       => true
                             )
                     );
                
		$objPHPExcel->getActiveSheet()->getStyle("B6:B$i")->getAlignment()->applyFromArray(
                             array(
                                 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
                                 'vertical'   => PHPExcel_Style_Alignment::VERTICAL_TOP,
                                 'rotation'   => 0,
                                 'wrap'       => true
                             )
                     );
                $objPHPExcel->getActiveSheet()->getStyle("C6:C$i")->getAlignment()->applyFromArray(
                             array(
                                 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
                                 'vertical'   => PHPExcel_Style_Alignment::VERTICAL_TOP,
                                 'rotation'   => 0,
                                 'wrap'       => true
                             )
                     );
                
                 $objPHPExcel->getActiveSheet()->getStyle("D6:D$i")->getAlignment()->applyFromArray(
                             array(
                                 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,
                                 'vertical'   => PHPExcel_Style_Alignment::VERTICAL_TOP,
                                 'rotation'   => 0,
                                 'wrap'       => true
                             )
                     );
		
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('A2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('C2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('D2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		
		$objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('A4')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('B4')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                $objPHPExcel->getActiveSheet()->getStyle('B5')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('C5')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		$objPHPExcel->getActiveSheet()->getStyle('D5')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
                
		$objPHPExcel->getActiveSheet()->setTitle('ReceivingAssigning');
		// Set active sheet index to the first sheet, so Excel opens this as the first sheet
		$objPHPExcel->setActiveSheetIndex(0);

		// Redirect output to a client’s web browser (Excel5)
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="TiepNhanPhanCong.xls"');
		header('Cache-Control: max-age=0');

      	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        ob_end_clean();
        
        $objWriter->save('php://output');
        $objPHPExcel->disconnectWorksheets();
        unset($objPHPExcel);
		Yii::app()->end();
        }

        /**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=ReceivingAssigning::model()->findByPk($id);
		$model->received_date = Common::mySQLDatetimeToString($model->received_date);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='receiving-assigning-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
